package rules

import (
	"bytes"
	"ddl_checker/internal/config"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"
)

// ExternalHTTPValidator 贸易2.0项目SQL检查 - 调用外部API进行验证
type ExternalHTTPValidator struct {
	*BaseAPIChecker
}

// NewExternalHTTPValidator 创建贸易2.0项目SQL检查
func NewExternalHTTPValidator() *ExternalHTTPValidator {
	enabled := false
	endpoint := config.GetString("HTTP_VALIDATOR_ENDPOINT", "")
	apiKey := config.GetString("HTTP_VALIDATOR_API_KEY", "")

	config := APICheckerConfig{
		Enabled:  enabled,
		Timeout:  30,
		Endpoint: endpoint,
		ApiKey:   apiKey,
	}
	return &ExternalHTTPValidator{
		BaseAPIChecker: NewBaseAPIChecker("贸易2.0项目SQL检查", config),
	}
}

// NewExternalHTTPValidatorEnabled 创建带启用状态的贸易2.0项目SQL检查
func NewExternalHTTPValidatorEnabled(enabled bool) *ExternalHTTPValidator {
	endpoint := config.GetString("HTTP_VALIDATOR_ENDPOINT", "")
	apiKey := config.GetString("HTTP_VALIDATOR_API_KEY", "")

	config := APICheckerConfig{
		Enabled:  enabled,
		Timeout:  30,
		Endpoint: endpoint,
		ApiKey:   apiKey,
	}
	return &ExternalHTTPValidator{
		BaseAPIChecker: NewBaseAPIChecker("贸易2.0项目SQL检查", config),
	}
}

// NewExternalHTTPValidatorWithConfig 创建带配置的贸易2.0项目SQL检查
func NewExternalHTTPValidatorWithConfig(config ValidatorConfig) *ExternalHTTPValidator {
	checkerConfig := APICheckerConfig{
		Enabled: config.Enabled,
		Timeout: 30,
	}

	// 从设置中读取配置
	if endpoint, ok := config.Settings["endpoint"].(string); ok {
		checkerConfig.Endpoint = endpoint
	}
	if apiKey, ok := config.Settings["api_key"].(string); ok {
		checkerConfig.ApiKey = apiKey
	}
	if timeout, ok := config.Settings["timeout"].(float64); ok {
		checkerConfig.Timeout = int(timeout)
	}

	return &ExternalHTTPValidator{
		BaseAPIChecker: NewBaseAPICheckerWithSettings("贸易2.0项目SQL检查", checkerConfig, config.Settings),
	}
}

// Validate 执行HTTP API检查
func (v *ExternalHTTPValidator) Validate(data DDLCheckData) APIResult {
	result := APIResult{
		Conclusion: APIConclusionFail,
		Details:    []string{"### 外部HTTP检查"},
	}

	if strings.TrimSpace(data.Script) == "" {
		result.Details = append(result.Details, "❌ 未提供DDL脚本")
		return result
	}

	config := v.GetConfig()
	if !config.Enabled || config.Endpoint == "" {
		result.Conclusion = APIConclusionFail
		result.Details = append(result.Details, "❌ HTTP检查器未配置")
		return result
	}

	// 调用外部API
	httpResult := v.callExternalHTTPAPI(data, config)
	result.Conclusion = httpResult.Conclusion
	result.Details = append(result.Details, httpResult.Details...)

	return result
}

// callExternalHTTPAPI 调用外部HTTP API
func (v *ExternalHTTPValidator) callExternalHTTPAPI(data DDLCheckData, config APICheckerConfig) APIResult {
	result := APIResult{
		Conclusion: APIConclusionFail,
		Details: []string{
			"📡 正在调用外部HTTP API...",
			fmt.Sprintf("🔗 API端点: %s", config.Endpoint),
		},
	}

	// 创建HTTP客户端
	client := &http.Client{
		Timeout: time.Duration(config.Timeout) * time.Second,
	}

	// 构建请求体
	requestBody := map[string]string{
		"data": strings.TrimSpace(data.Script),
	}
	jsonBody, err := json.Marshal(requestBody)
	if err != nil {
		result.Details = append(result.Details, fmt.Sprintf("❌ 请求体序列化失败: %v", err))
		return result
	}

	// 创建HTTP请求
	req, err := http.NewRequest("POST", config.Endpoint, bytes.NewBuffer(jsonBody))
	if err != nil {
		result.Details = append(result.Details, fmt.Sprintf("❌ 创建请求失败: %v", err))
		return result
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	if config.ApiKey != "" {
		req.Header.Set("Authorization", "Bearer "+config.ApiKey)
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		result.Details = append(result.Details, fmt.Sprintf("❌ HTTP请求失败: %v", err))
		return result
	}
	defer resp.Body.Close()

	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		result.Details = append(result.Details, fmt.Sprintf("❌ 读取响应失败: %v", err))
		return result
	}

	// 解析响应
	result.Details = append(result.Details, "✅ HTTP API调用成功")
	result.Details = append(result.Details, fmt.Sprintf("📊 响应状态码: %d", resp.StatusCode))

	// 提取output字段
	output, err := extractOutputFromResponse(respBody)
	if err != nil {
		result.Details = append(result.Details, fmt.Sprintf("❌ 解析响应失败: %v", err))
		return result
	}

	if output != "" {
		result.Details = append(result.Details, "📋 API返回结果:")
		// 将output按行分割并添加到详情中
		lines := strings.Split(output, "\n")
		for _, line := range lines {
			if strings.TrimSpace(line) != "" {
				result.Details = append(result.Details, line)
			}
		}
		result.Conclusion = APIConclusionPass
	} else {
		result.Details = append(result.Details, "⚠️ API返回结果为空")
		result.Conclusion = APIConclusionWarning
	}

	return result
}

// getEnvWithDefault 获取环境变量，如果不存在则返回默认值

// extractOutputFromResponse 从响应体中提取output字段
func extractOutputFromResponse(respBody []byte) (string, error) {
	var response map[string]interface{}
	if err := json.Unmarshal(respBody, &response); err != nil {
		return "", fmt.Errorf("JSON解析失败: %v", err)
	}

	if output, ok := response["output"].(string); ok {
		return output, nil
	}

	return "", fmt.Errorf("响应中未找到output字段")
}
